package org.unt.thread;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

public class Test {

	private static Logger log = Logger.getLogger("Test");

	public static Map map = null;
	public static List tables = null;

	public static void main(String[] args) throws InterruptedException {
		new Test().process();
	}

	public void process() throws InterruptedException {

		new Monitor().start();

		tables = getTables();
		map = getAsMap(tables);

		for (Iterator iterator = tables.iterator(); iterator.hasNext();) {

			String table = (String) iterator.next();

			while (TaskRunner.avaibleThreadsAmount < 1) {
				Thread.sleep(500);
			}

			TaskRunner.avaibleThreadsAmount--;

			TaskRunner my = new TaskRunner(table);
			my.start();
		}
	}

	public static State getGeneralState() {

		StringBuffer bufAW = new StringBuffer("AW > ");
		StringBuffer bufOG = new StringBuffer("OG > ");
		StringBuffer bufFI = new StringBuffer("FI > ");

		for (Iterator iterator = tables.iterator(); iterator.hasNext();) {

			String table = (String) iterator.next();
			String state = (String) Test.map.get(table);

			if ("AW".equals(state)) {
				bufAW.append(table + "  ");
			} else if ("OG".equals(state)) {
				bufOG.append(table + "  ");
			} else if ("FI".equals(state)) {
				bufFI.append(table + "  ");
			}
		}

		return new State("\n" + bufAW.toString() + "\n" + bufOG.toString() + "\n" + bufFI.toString(), bufAW.length() == 5 && bufOG.length() == 5);
	}

	public Map getAsMap(List tables) {

		Map map = new HashMap();

		for (Iterator iterator = tables.iterator(); iterator.hasNext();) {
			String table = (String) iterator.next();
			map.put(table, "AW");
		}

		return map;
	}

	public List getTables() {

		List tables = new ArrayList();

		tables.add("A");
		tables.add("B");
		tables.add("C");
		tables.add("D");
		tables.add("E");
		tables.add("F");
		tables.add("G");
		tables.add("H");
		tables.add("I");
		tables.add("J");
		tables.add("K");
		tables.add("L");
		tables.add("M");
		tables.add("N");
		tables.add("O");
		tables.add("P");
		tables.add("Q");
		tables.add("R");
		tables.add("S");
		tables.add("T");

		return tables;
	}

	public class Monitor extends Thread {

		public void run() {

			while (true) {

				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				Test.State state = Test.getGeneralState();

				log.info(state.str);

				if (state.finished) {
					break;
				}
			}
		}
	}

	private static class State {

		public String str;
		public boolean finished;

		public State(String str, boolean finished) {
			super();
			this.str = str;
			this.finished = finished;
		}
	}
}
